package ffr;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;

import vo.ConnectDbase;
import vo.RegisterDAO;
import vo.User;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/registerservlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String realname = request.getParameter("realname");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if(username==null||username.trim().isEmpty()){
			response.setContentType("text/html; charset=UTF-8");
			response.getWriter().write("<script>alert('用户名不能为空！');history.back();</script>");
			return;
		}
		if(password==null||password.trim().isEmpty()){
			response.setContentType("text/html; charset=UTF-8");
			response.getWriter().write("<script>alert('密码不能为空！');history.back();</script>");
			return;
		}
		
		User user = new User(username, password, realname);
		RegisterDAO dao = new RegisterDAO();
		try {
			ConnectDbase db = new ConnectDbase();
			Connection con = (Connection) db.getConnect();
			boolean res = dao.register(con, user);
			if(res) {
				response.setContentType("text/html; charset=UTF-8");
				response.getWriter().write("<script>alert('注册成功！');history.go(-2);</script>");
			}else {
				response.setContentType("text/html; charset=UTF-8");
				response.getWriter().write("<script>alert('注册失败，该用户名已存在！');history.back();</script>");
				return;
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

}
